<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Models;

use \Sun\Sun;

class Session implements \Sun\IModel {
    private $keys;
    private $auth;

    public function __construct($id = null) {
        $this->keys = array($id."login", $id."profile");
        $this->auth = (@$_SESSION[$this->keys[0]] == "yes");
    }

    public function IsLogin() {
        return $this->auth;
    }

    public function Profile() {
        if (!$this->IsLogin()) return null;
        return @$_SESSION[$this->keys[1]];
    }

    public function UserType() {
        if (!$this->IsLogin()) return null;
        return @$_SESSION[$this->keys[1]]['sense'];
    }

    public function Login($p) {
        $db = new DB();
        $login = $db->quote($p['login']);
        $pass = $db->quote($p['pass']);
        $query = "SELECT user_id \"id\", fullname,
                login, pass, \"user\".type_id, user_type.name \"type\", sense,
                reg_date, reg_comp
            FROM \"user\" JOIN user_type using(type_id)
            WHERE \"user\".type_id = '{$p['type_id']}'
                AND login = {$login}
                AND pass = {$pass}";
        $res = $db->SafeQuery($query);
        if ($res && $res->rowCount() == 1) {
            $res = $res->fetch(DB::FETCH_ASSOC);
            $_SESSION[$this->keys[1]] = &$res;
            $_SESSION[$this->keys[0]] = "yes";
            return $this->auth = true;
        }
        return false;
    }

    public function Logout() {
        $this->auth = false;
        unset($_SESSION[$this->keys[0]]);
        unset($_SESSION[$this->keys[1]]);
    }

    public function UserId() {
        $prof = $this->Profile();
        return $prof['id'];
    }

}
